package com.emm.yixun.customer.service.impl;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.jws.WebService;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.emm.yixun.basic.service.CustTagService;
import com.emm.yixun.basic.service.ProjectAnswerService;
import com.emm.yixun.basic.service.ProjectQuestionService;
import com.emm.yixun.basic.service.ProjectQuestionnaireService;
import com.emm.yixun.common.exception.ResponseCode;
import com.emm.yixun.common.model.CustTag;
import com.emm.yixun.common.model.ProjectAnswer;
import com.emm.yixun.common.model.ProjectQuestion;
import com.emm.yixun.common.model.ProjectQuestionInfo;
import com.emm.yixun.common.model.ProjectQuestionnaire;
import com.emm.yixun.common.model.ProjectQuestionnaireInfo;
import com.emm.yixun.common.model.dto.CustTagDto;
import com.emm.yixun.common.model.dto.ProjectAnswerDto;
import com.emm.yixun.common.model.dto.ProjectQuestionDto;
import com.emm.yixun.common.model.dto.ProjectQuestionnaireDto;
import com.emm.yixun.common.model.enums.AnswerTypeEnum;
import com.emm.yixun.common.model.enums.DelFlagEnum;
import com.emm.yixun.common.model.enums.IsAvlidEnum;
import com.emm.yixun.common.page.Page;
import com.emm.yixun.common.response.Response;
import com.emm.yixun.common.response.ResponseList;
import com.emm.yixun.customer.service.ProjectQuestionServiceFacade;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

@Service("projectQuestionServiceFacade")
@WebService(name="com.emm.yixun.customer.service.ProjectQuestionServiceFacade")
public class ProjectQuestionServiceFacadeImpl implements ProjectQuestionServiceFacade{
	private  final Logger   logger = LoggerFactory.getLogger(this.getClass()); 
	
	@Autowired
	private ProjectQuestionService service;
	
	@Autowired
	private ProjectAnswerService projectAnswerService;
	
	@Autowired
	private ProjectQuestionnaireService projectQuestionnaireService;
	
	@Autowired
	private CustTagService custTagService;

	@Override
	public Response<ProjectQuestionDto> save(ProjectQuestionDto dto) {
		Response<ProjectQuestionDto> response=new Response<ProjectQuestionDto>();
		try {
			if(null==dto){
				response.fail(ResponseCode.PARAM_INVALID.getCode(), ResponseCode.PARAM_INVALID.formatMessage("保存"));
				return response;
			}
			ProjectQuestionDto mDto=service.create(dto);
			if(null==mDto){
				response.fail("80000", "保存数据错误");
				return response;
			}
			response.success(mDto);
		} catch (Exception e) {
			response.fail(ResponseCode.SYSTEM_EXCEPTION.getCode(), ResponseCode.SYSTEM_EXCEPTION.getMessageTemplate());
			logger.error("保存数据错误：{}",e);
		}
		return response;
	}

	@Override
	public Response<Integer> updateByPrimaryKey(ProjectQuestionDto dto,Boolean selective) {
		Response<Integer> response=new Response<Integer>();
		try {
			if(null==selective || null==dto || null==dto.getId()){
				response.fail(ResponseCode.PARAM_INVALID.getCode(), ResponseCode.PARAM_INVALID.formatMessage("更新"));
				return response;
			}
			
			if(selective){
				int count=service.update(dto);
				if(count>0){
					response.success(Integer.valueOf(count));
				}else{
					response.fail("90001", "更新数据失败");
				}
			}else{
				response.fail("90000", "暂未实现,修改参数selective=true即可");
			}
		} catch (Exception e) {
			response.fail(ResponseCode.SYSTEM_EXCEPTION.getCode(), ResponseCode.SYSTEM_EXCEPTION.getMessageTemplate());
			logger.error("更新数据错误：{}",e);
		}
		return response;
	}

	@Override
	public Response<Integer> deleteByPrimaryKey(Long id) {
		Response<Integer> response=new Response<Integer>();
		try {
			if(null==id){
				response.fail(ResponseCode.PARAM_INVALID.getCode(), ResponseCode.PARAM_INVALID.formatMessage("删除"));
				return response;
			}
			ProjectQuestionDto mDto=new ProjectQuestionDto();
			mDto.setId(id);
			int count=service.destroy(mDto);
			if(count>0){
				response.success(Integer.valueOf(count));
			}else{
				response.fail("90001", "删除数据失败");
			}
		} catch (Exception e) {
			response.fail(ResponseCode.SYSTEM_EXCEPTION.getCode(), ResponseCode.SYSTEM_EXCEPTION.getMessageTemplate());
			logger.error("删除数据错误：{}",e);
		}
		return response;
	}
	
    @Override
	public Response<ProjectQuestion> findById(Long id) {
		Response<ProjectQuestion> response=new Response<ProjectQuestion>();
		try {
			if(null==id){
				response.fail(ResponseCode.PARAM_INVALID.getCode(), ResponseCode.PARAM_INVALID.formatMessage("主键查询"));
				return response;
			}
			ProjectQuestion entity=service.selectById(id);
			if(null==entity){
				response.fail("90001", "主键查询数据失败");
			}else{
				response.success(entity);;
			}
		} catch (Exception e) {
			response.fail(ResponseCode.SYSTEM_EXCEPTION.getCode(), ResponseCode.SYSTEM_EXCEPTION.getMessageTemplate());
			logger.error("主键查询数据错误：{}",e);
		}
		return response;
	}

	@Override
	public ResponseList<ProjectQuestion> findByDto(ProjectQuestionDto dto) {
		ResponseList<ProjectQuestion> response=new ResponseList<ProjectQuestion>();
		try {
			if(null==dto){
				response.fail(ResponseCode.PARAM_INVALID.getCode(), ResponseCode.PARAM_INVALID.formatMessage("查询"));
				return response;
			}
			List<ProjectQuestion> list=service.selectListByDto(dto);
			if(null==list){
				response.fail(ResponseCode.NO_DATA_FOUND.getCode(), ResponseCode.NO_DATA_FOUND.formatMessage("查询"));
				return response;
			}
			response.success(list);
		} catch (Exception e) {
			response.fail(ResponseCode.SYSTEM_EXCEPTION.getCode(), ResponseCode.SYSTEM_EXCEPTION.getMessageTemplate());
			logger.error("查询数据错误：{}",e);
		}
		return response;
	}

	@Override
	public Page<ProjectQuestion> findPageByDto(ProjectQuestionDto dto, Integer begin,Integer row) {
		Page<ProjectQuestion> response=new Page<ProjectQuestion>();
		try {
			if(null==dto || null==begin || null==row){
				response.setSuccess(false);
				response.setErrorMsg("参数不合法");
				return response;
			}
			Page<ProjectQuestion> page = service.getPageModel(dto, begin, row);
			if(null==page.getRows()){
				response.setSuccess(false);
				response.setErrorMsg("分页数据不存在");
				return response;
			}
			response=page;
			response.setSuccess(true);
		} catch (Exception e) {
			response.setSuccess(false);
			response.setErrorMsg(ResponseCode.SYSTEM_EXCEPTION.getMessageTemplate());
			logger.error("查询分页数据错误：{}",e);
		}
		return response;
	}
	
	@Override
	public ResponseList<ProjectQuestionInfo> questionList(ProjectQuestionDto dto) {
		ResponseList<ProjectQuestionInfo> response=new ResponseList<ProjectQuestionInfo>();
		try {
			if(null==dto){
				response.fail(ResponseCode.PARAM_INVALID.getCode(), ResponseCode.PARAM_INVALID.formatMessage("查询"));
				return response;
			}
			List<ProjectQuestionInfo> infoList = new ArrayList<ProjectQuestionInfo>();
			dto.addAsc("sort");
			List<ProjectQuestion> list = service.selectListByDto(dto);
			if(null==list){
				response.fail(ResponseCode.NO_DATA_FOUND.getCode(), ResponseCode.NO_DATA_FOUND.formatMessage("查询"));
				return response;
			}
			//获取答案及其它信息
			for(ProjectQuestion question : list){
				ProjectQuestionInfo info = new ProjectQuestionInfo();
				BeanUtils.copyProperties(question, info);
				
				//查询答案表
				ProjectAnswerDto answerDto = new ProjectAnswerDto();
				answerDto.setProjectQuestionId(question.getId()); //问题ID
				answerDto.setIsValid(IsAvlidEnum.AVILD.getNo());
				answerDto.setDelFlag(DelFlagEnum.UNDEL.getNo());
				List<ProjectAnswer> answerList = projectAnswerService.selectListByDto(answerDto);
				JSONArray arrayJson = new JSONArray(); //保存答案ID和内容
				JSONArray array = new JSONArray(); //仅保存答案内容
				for(ProjectAnswer answer : answerList){
					JSONObject json = new JSONObject();
					json.put("id", answer.getId());
					json.put("answer", answer.getAnswer());
					arrayJson.add(json);
					array.add(answer.getAnswer());
				}
				info.setAnswer(array.toString());
				info.setArrayJson(arrayJson.toString());
				infoList.add(info);
			}
			response.success(infoList);
		} catch (Exception e) {
			response.fail(ResponseCode.SYSTEM_EXCEPTION.getCode(), ResponseCode.SYSTEM_EXCEPTION.getMessageTemplate());
			logger.error("查询数据错误：{}",e);
		}
		return response;
	}

	@Override
	public Response<String> saveQuestionnaire(ProjectQuestionInfo info) {
		Response<String> response=new Response<String>();
		try {
			if(null==info){
				response.fail(ResponseCode.PARAM_INVALID.getCode(), ResponseCode.PARAM_INVALID.formatMessage("保存"));
				return response;
			}
			//查询项目问卷主表，并获取项目ID
			ProjectQuestionnaire pq = projectQuestionnaireService
					.selectById(info.getProjectQuestionnaireId());
			if(pq == null){
				response.fail(ResponseCode.PARAM_INVALID.getCode(), ResponseCode.PARAM_INVALID.formatMessage("保存"));
				return response;
			}
			//保存问题及答案
			saveQuestion(info, pq.getProjectId());
			
			//更新模板修改人与修改时间
			ProjectQuestionnaireDto model = new ProjectQuestionnaireDto();
			model.setId(info.getProjectQuestionnaireId());
			model.setUpdateUser(info.getCreateUser());
			model.setUpdateTime(info.getCreateTime());
			projectQuestionnaireService.update(model);
			
			response.success("1");
		} catch (Exception e) {
			response.fail(ResponseCode.SYSTEM_EXCEPTION.getCode(), ResponseCode.SYSTEM_EXCEPTION.getMessageTemplate());
			logger.error("保存数据错误：{}",e);
		}
		return response;
	}
	/**
	 * 保存问卷
	 * @param QuestionnaireQuestionInfo
	 * @return
	 */
	private Response<String> saveQuestion(ProjectQuestionInfo info, Long projectId){
		Response<String> response = new Response<String>();
		//判断问卷是否已保存过，如已保存，则删除原纪录(逻辑删除)
		ProjectQuestionDto entity = new ProjectQuestionDto();
		entity.setProjectQuestionnaireId(info.getProjectQuestionnaireId());
		entity.setProjectId(projectId);
		List<ProjectQuestion> list = service.selectListByDto(entity);
		for(int i = 0; i < list.size(); i++){
			ProjectQuestion question = (ProjectQuestion)list.get(i);
			ProjectQuestionDto dto = new ProjectQuestionDto();
			dto.setId(question.getId());
			dto.setIsValid(IsAvlidEnum.UNAVILD.getNo());
			dto.setDelFlag(DelFlagEnum.DEL.getNo());
			service.update(dto);
			
			//删除已保存的答案
			ProjectAnswerDto answerEntity = new ProjectAnswerDto();
			answerEntity.setProjectQuestionId(question.getId());
			List<ProjectAnswer> answerList = projectAnswerService.selectListByDto(answerEntity);
			for(int l = 0; l < answerList.size(); l++){
				ProjectAnswer answer = (ProjectAnswer)answerList.get(l);
				ProjectAnswerDto answerDto = new ProjectAnswerDto();
				answerDto.setId(answer.getId());
				answerDto.setIsValid(IsAvlidEnum.UNAVILD.getNo());
				answerDto.setDelFlag(DelFlagEnum.DEL.getNo());
				projectAnswerService.update(answerDto);
			}
		}
		
		//解析arrayJson，获取问题内容，并循环保存
		JSONArray array = JSONArray.fromObject(info.getArrayJson());
		for(int i = 0; i < array.size(); i++){
			JSONObject json = (JSONObject)array.get(i);
			ProjectQuestionDto dto = new ProjectQuestionDto();
			dto.setProjectQuestionnaireId(info.getProjectQuestionnaireId()); //项目问卷主表ID
			dto.setQuestion(json.getString("question")); //问题名称
			dto.setQuestionnaireDescribe(json.getString("questionnaireDescribe")); //问题描述
			dto.setProblemCode(json.getString("problemCode")); //问题编码
			dto.setAnswerType(json.getString("answerType")); //答案类型
			dto.setIsRequired(json.getString("isRequired")); //是否必填
			dto.setLevel(Long.parseLong(json.getString("level"))); //问题级别
			dto.setTagExtId(StringUtils.isBlank(json.getString("tagExtId"))?
                    null:Long.parseLong(json.getString("tagExtId"))); //客户标签问题ID
			dto.setProjectId(projectId);
			dto.setSort(Long.parseLong(i+1+"")); //排序
			dto.setPage(1L); //分页（默认为1页）
			dto.setMerchantId(info.getMerchantId()); //商户ID
			dto.setCreateUser(info.getCreateUser());
			dto.setIsValid(IsAvlidEnum.AVILD.getNo());
			dto.setDelFlag(DelFlagEnum.UNDEL.getNo());
			ProjectQuestionDto qq = service.create(dto);
			//保存答案
			saveAnswer(json.getString("answer"), qq);
		}
		
		response.success("1");
		return response;
	}
	
	/**
	 * 保存答案
	 * @param arrayJson
	 * @param id
	 * @param merchantId
	 * @return
	 */
	private Response<String> saveAnswer(String arrayJson, ProjectQuestionDto qq){
		Response<String> response = new Response<String>();
		//删除原答案
		ProjectAnswerDto entity = new ProjectAnswerDto();
		entity.setProjectQuestionId(qq.getId());
		List<ProjectAnswer> list = projectAnswerService.selectListByDto(entity);
		for(int i = 0; i < list.size(); i++){
			ProjectAnswer answer = (ProjectAnswer)list.get(i);
			ProjectAnswerDto dto = new ProjectAnswerDto();
			dto.setId(answer.getId());
			projectAnswerService.destroy(dto);
		}
		//解析json，并保存新答案
		JSONArray array = JSONArray.fromObject(arrayJson);
		for(int i = 0; i < array.size(); i++){
			String answer = array.get(i).toString();
			if(StringUtils.isBlank(answer)){
				continue;
			}
			ProjectAnswerDto dto = new ProjectAnswerDto();
			dto.setProjectQuestionId(qq.getId()); //问题ID
			dto.setAnswer(answer);	//答案内容
			dto.setSort(Long.parseLong(i+1+"")); //排序
			dto.setMerchantId(qq.getMerchantId()); //商户ID
			dto.setCreateTime(qq.getCreateTime());
			dto.setCreateUser(qq.getCreateUser());
			dto.setIsValid(IsAvlidEnum.AVILD.getNo());
			dto.setDelFlag(DelFlagEnum.UNDEL.getNo());
			projectAnswerService.create(dto);
		}
		return response;
	}
	
	@Override
	public ResponseList<ProjectQuestionInfo> questionAyalyzeList(ProjectQuestionDto dto) {
		ResponseList<ProjectQuestionInfo> response=new ResponseList<ProjectQuestionInfo>();
		try {
			if(null==dto){
				response.fail(ResponseCode.PARAM_INVALID.getCode(), ResponseCode.PARAM_INVALID.formatMessage("查询"));
				return response;
			}
			List<ProjectQuestionInfo> infoList = new ArrayList<ProjectQuestionInfo>();
			dto.addAsc("sort");
			List<ProjectQuestion> list = service.selectListByDto(dto);
			if(null==list){
				response.fail(ResponseCode.NO_DATA_FOUND.getCode(), ResponseCode.NO_DATA_FOUND.formatMessage("查询"));
				return response;
			}
			//问卷答题总数
			ProjectQuestionnaireDto pqDto = new ProjectQuestionnaireDto();
			pqDto.setId(dto.getProjectQuestionnaireId());
			int questionnaireAnsweredCount = projectQuestionnaireService.findQuestionnaireAnsweredCount(pqDto);
			
			//获取问卷题目所有的文本题汇总
			List<ProjectQuestionnaireInfo> pqiTextList = projectQuestionnaireService.findAyalyzeTextByDto(pqDto);
			Map<Integer, Integer> answerTextMap = new HashMap<Integer, Integer>();
			if(null != pqiTextList && pqiTextList.size() > 0){
				for(ProjectQuestionnaireInfo pqiText: pqiTextList){
					answerTextMap.put(pqiText.getProjectQuestionId(), pqiText.getAnswerCount());
				}
			}
			
			//选择题题目答题次数汇总
			List<ProjectQuestionnaireInfo> choosenAnsweredList = projectQuestionnaireService.findChoosenQuestionAnsweredCountByDto(pqDto);
			Map<Integer, Integer> choosenAnsweredMap = new HashMap<Integer, Integer>();
			if(null != choosenAnsweredList && choosenAnsweredList.size() > 0){
				for(ProjectQuestionnaireInfo pqiChoose: choosenAnsweredList){
					choosenAnsweredMap.put(pqiChoose.getProjectQuestionId(), pqiChoose.getAnswerCount());
				}
			}
			
			//获取问卷题目所有的答题结果汇总
			pqDto = new ProjectQuestionnaireDto();
			pqDto.setId(dto.getProjectQuestionnaireId());
			List<ProjectQuestionnaireInfo> pqiChooseList = projectQuestionnaireService.findAyalyzeAnswerByDto(pqDto);
			Map<Integer, Integer> answerChooseMap = new HashMap<Integer, Integer>();
			if(null != pqiChooseList && pqiChooseList.size() > 0){
				for(ProjectQuestionnaireInfo pqi: pqiChooseList){
					answerChooseMap.put(pqi.getProjectAnswerId(), pqi.getAnswerCount());
				}
			}
			//获取答案及其它信息
			for(ProjectQuestion question : list){
				int pqId = Integer.valueOf(String.valueOf(question.getId()));
				int totalChooseAnswer = 0;
				ProjectQuestionInfo info = new ProjectQuestionInfo();
				//计算文本答题率
				if(AnswerTypeEnum.INPUT.getNo().equals(question.getAnswerType())){
					BigDecimal ratio = new BigDecimal(0);
					info.setTextRate(String.valueOf(ratio));
					if(null != question.getId()){
						ratio =  getRatio(new BigDecimal(100),
								new BigDecimal(questionnaireAnsweredCount),
								new BigDecimal(answerTextMap.get(Integer.parseInt(String.valueOf(question.getId())))==null?0:answerTextMap.get(Integer.parseInt(String.valueOf(question.getId())))),
								3);
						info.setTextRate(String.valueOf(ratio));
					}
				}else{
					BigDecimal ratio = new BigDecimal(0);
					info.setTextRate(String.valueOf(ratio));
					if(null != question.getId()){
						ratio =  getRatio(new BigDecimal(100),
								new BigDecimal(questionnaireAnsweredCount),
								new BigDecimal(choosenAnsweredMap.get(Integer.parseInt(String.valueOf(question.getId())))==null?0:choosenAnsweredMap.get(Integer.parseInt(String.valueOf(question.getId())))),
								3);
						info.setTextRate(String.valueOf(ratio));
					}
				}
				BeanUtils.copyProperties(question, info);
				
				//统计当前选项的答题总数
				if(null != pqiChooseList && pqiChooseList.size() > 0){
					for(ProjectQuestionnaireInfo pqi: pqiChooseList){
						if(pqId == pqi.getProjectQuestionId()){
							totalChooseAnswer += pqi.getAnswerCount();
						}
					}
				}
				//查询答案表
				ProjectAnswerDto answerDto = new ProjectAnswerDto();
				answerDto.setProjectQuestionId(question.getId()); //问题ID
				answerDto.setIsValid(IsAvlidEnum.AVILD.getNo());
				answerDto.setDelFlag(DelFlagEnum.UNDEL.getNo());
				List<ProjectAnswer> answerList = projectAnswerService.selectListByDto(answerDto);
				JSONArray arrayJson = new JSONArray(); //保存答案ID和内容
				JSONArray array = new JSONArray(); //仅保存答案内容
				for(ProjectAnswer answer : answerList){
					JSONObject json = new JSONObject();
					json.put("id", answer.getId());
					json.put("answer", answer.getAnswer());
					//题目选项对应的总答案数量
					int answerCount = answerChooseMap.get(Integer.parseInt(String.valueOf(answer.getId())))==null?0:answerChooseMap.get(Integer.parseInt(String.valueOf(answer.getId())));
					json.put("rate", getRatio(new BigDecimal(100), new BigDecimal(totalChooseAnswer), new BigDecimal(answerCount),3));
					arrayJson.add(json);
					array.add(answer.getAnswer());
				}
				info.setAnswer(array.toString());
				info.setArrayJson(arrayJson.toString());
				infoList.add(info);
			}
			response.success(infoList);
		} catch (Exception e) {
			e.printStackTrace();
			response.fail(ResponseCode.SYSTEM_EXCEPTION.getCode(), ResponseCode.SYSTEM_EXCEPTION.getMessageTemplate());
			logger.error("查询数据错误：{}",e);
		}
		return response;
	}
	
	/**
	 * 计算答题率
	 * @param ro 百分比默认100的倍数
	 * @param cusNum 回答的人数
	 * @param num 选项选择数
	 * @return
	 */
	private BigDecimal getRatio(BigDecimal ro, BigDecimal total, BigDecimal count, int point){
		//当答题数或选择数为0时，不进行计算
		BigDecimal n = new BigDecimal("0");
		if(null == total || null == count){
			return n;
		}
		if(total.compareTo(n) == 0 || 
				count.compareTo(n) == 0){
			return n;
		}
		//计算比例
		BigDecimal ratio = count.divide(total,point, BigDecimal.ROUND_HALF_UP).multiply(ro);
		return ratio;
	}
	
	@Override
    public Response<String> getCusTagList(ProjectQuestionDto dto, Long customerId) {
        Response<String> response=new Response<String>();
        try {
            if(null==dto){
                response.fail(ResponseCode.PARAM_INVALID.getCode(), ResponseCode.PARAM_INVALID.formatMessage("保存"));
                return response;
            }
            /**
             * 原需求需要过滤问卷中已有的问题，新需求去掉限制 —— 禅道需求ID：7073-客户标签优化20180327
             *
            List<ProjectQuestion> list = service.selectListByDto(dto);
            if(list == null){
                response.fail(ResponseCode.PARAM_INVALID.getCode(), ResponseCode.PARAM_INVALID.formatMessage("保存"));
                return response;
            }
            JSONArray array = new JSONArray();
            for(ProjectQuestion info : list){
                array.add(info.getTagExtId());
            }*/
            JSONArray array = new JSONArray();
            //有客户ID传入时，查询客户是否有以答标签
            if(customerId != null){
                CustTagDto entity = new CustTagDto();
                entity.setCustomerId(customerId);
                List<CustTag> custTaglist = custTagService.selectListByDto(entity);
                if(custTaglist != null){
                    for(CustTag custTag : custTaglist){
                        array.add(custTag.getTagExtId()); 
                    }
                }
            }
            
            //拼接条件
            String sql = null;
            if(array.size() > 0){
                sql = array.toString().replace("["," ext.id not in (").replace("]",")");
            }
            response.success(sql);
        } catch (Exception e) {
            response.fail(ResponseCode.SYSTEM_EXCEPTION.getCode(), ResponseCode.SYSTEM_EXCEPTION.getMessageTemplate());
            logger.error("保存数据错误：{}",e);
        }
        return response;
    }
}
